package me.algo.array;

import java.util.Objects;

/**
 * @author guozheng
 * @date 2024/4/13
 */
public class A2 {

    public static void main(String[] args) {
        int[] num = {4,5,6,7,0,1,2};
        int target = 0;
        System.out.println(search(num, target));
    }

    /**
     * 33. 搜索旋转排序数组
     * @param nums
     * @param target
     * @return
     * TODO error
     */
    public static int search(int[] nums, int target) {
        if (Objects.isNull(nums)) {
            return -1;
        }
        if (nums.length == 1) {
            if (nums[0] == target) {
                return 0;
            } else {
                return -1;
            }
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            int midVal = nums[mid];
            if (target == midVal) {
                return mid;
            } else if (nums[0] <= mid) {
                // 此时假设是有序的数组  进行二分查找
                if (nums[0] <= target && target < midVal) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } else {
                if (midVal < target && target <= nums[nums.length - 1]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}
